import { marked } from "marked";
import hljs from "@/services/highlight";
import { META } from "@/config/app.config";

marked.setOptions({
    gfm: true,
    sanitize: false,
    breaks: false,
    pedantic: false,
    smartLists: true,
    smartypants: false,
    highlight(code, language) {
        return hljs.getLanguage(language)
            ? hljs.highlight(language, code).value
            : hljs.highlightAuto(code).value
    }
});

const customRenderer = new marked.Renderer();

// 段落解析
customRenderer.paragraph = text => `<p>${text}</p>`;

// 标题解析
customRenderer.heading = (text, level, raw) => {
    const id = raw.toLowerCase().replace(/[^a-zA-Z0-9\u4E00-\u9FA5]+/g, '-');
    return `<h${level} id=${id} alt=${id} title=${id}>${text}</h${level}>`;
};

// 对连接进行权重防流和新窗处理
customRenderer.link = (href, title, text) => {
    const isSelf = href.includes(META.url);
    const textIsImage = text.includes('<img');
    const linkHtml = `
    <a
      href="${href}"
      target="_blank"
      class="${textIsImage ? 'image-link' : 'link'}"
      title="${title || (textIsImage ? href : text)}"
      ${isSelf ? '' : 'rel="external nofollow noopenter"'}
    >
      ${text}
    </a>
  `
    return linkHtml.replace(/\s+/g, ' ').replace(/\n/g, ' ');
}

// 对图片进行弹窗处理
customRenderer.image = (src, title, alt) => {
    // 仅替换 HTTP 链接为 proxy
    // src = src.replace(/^http:\/\//gi, `${API_CONFIG.PROXY}/`);
    // const imageHtml = `
    //   <img
    //     class="lozad"
    //     data-src="${src}"
    //     title="${title || alt || appConfig.meta.url}" 
    //     alt="${alt || title || src}"
    //     onclick="if (window.utils) window.utils.openImgPopup('${src}')"
    //   />
    // `;
    return (`
    <img
      class="lozad"
      src="${src}"
      data-src="${src}"
      title="${title || alt}" 
      alt="${alt || title || src}"
    />
  `).replace(/\s+/g, ' ').replace(/\n/g, ' ');
};

// 代码解析器（行号处理）
customRenderer.code = function (code, lang, escaped) {
    if (this.options.highlight) {
        const output = this.options.highlight(code, lang || "") || "";
        if (output != null && output !== code) {
            escaped = true;
            code = output;
        }
    }
    const lineNumbers = code
        .split('\n')
        .map((l, i) => `<li class="code-line-number">${i + 1}</li>`.replace(/\s+/g, ' '))
        .join('');
    const preHtml = lang
        ? `
            <pre data-lang="${lang}">
            <ul class="code-lines">${lineNumbers}</ul>
            <code class="${this.options.langPrefix}${escape(lang)}">${escaped ? code : escape(code)}\n</code>
            </pre>\n
        `
        : `
        <pre>
            <ul class="code-lines">${lineNumbers}</ul>
            <code>${escaped ? code : escape(code)}\n</code>
        </pre>
        `
    return preHtml;
};

export const markdownToHTML = (markdown, options) => {
    if (!markdown || typeof markdown !== "string") {
        return "";
    }

    return marked(markdown, {
        sanitize: !options?.html,
        renderer: customRenderer
    })
}
